﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TCM.DbContextt;
using TCM.Models;


namespace TCM.Forms
{
    public partial class CategoriesList : Form
    {

        BaseContext db;

        public CategoriesList()
        {
            InitializeComponent();
            db = new BaseContext();

            db.Categories.Load();

            dataGridView1.DataSource = db.Categories.Local.ToBindingList();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CategoriesManager CategoriesManager = new CategoriesManager();
            var result = CategoriesManager.ShowDialog(this);

            if (result == DialogResult.Cancel)
                return;

            Category Category = new Category();

            Category.CategoryID = Guid.NewGuid();
            Category.Name = CategoriesManager.textBox1.Text;

            db.Categories.Add(Category);
            db.SaveChanges();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Категорию выбери");
                return;
            }
            int index = dataGridView1.SelectedRows[0].Index;
            Guid id = Guid.Empty;
            bool parse = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);

            if (!parse)
                return;
        
            Category Category = db.Categories.Find(id);

            db.Categories.Remove(Category);

            db.SaveChanges();

            MessageBox.Show("Удаление прошло успешно");          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int index = dataGridView1.SelectedRows[0].Index;
            Guid id = Guid.Empty;
            bool parse = Guid.TryParse(dataGridView1[0, index].Value.ToString(), out id);

            if (!parse)
                return;

            Category Category = new Category();

            Category = db.Categories.Find(id);

            CategoriesManager CategoriesManager = new CategoriesManager();

            CategoriesManager.textBox1.Text = Category.Name;

            var result = CategoriesManager.ShowDialog(this);

            if (result == DialogResult.Cancel)
                return;

            Category.Name = CategoriesManager.textBox1.Text;

            db.Entry(Category).State = EntityState.Modified;

            db.SaveChanges();

            dataGridView1.Refresh();

        }





    }
}
